package com.genntii.examManager.common.filter;

import com.genntii.examManager.common.constant.CommonConstant;
import com.genntii.examManager.common.constant.RequestHeaderConstant;
import com.genntii.examManager.common.properties.JwtProperties;
import com.genntii.examManager.common.security.DBUserManager;
import com.genntii.examManager.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private DBUserManager dbUserManager;

    @Qualifier("filterChain")
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getServletPath().contains("/user/login")||request.getServletPath().contains("/user/register") || request.getServletPath().contains("/user/sendCaptcha")){
            filterChain.doFilter(request,response);
            return;
        }
        final String token = request.getHeader("Authorization");
        final String clientType = request.getHeader("Client-Type");

        if (token == null){
            filterChain.doFilter(request,response);
            return;
        }

        Claims claims = null;
        if (Objects.equals(clientType, RequestHeaderConstant.USER_CLIENT)){
            claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(),token);
            int id = (int) claims.get("id");
            String username = String.valueOf(claims.get("username"));

            if (username != null){
//            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null){
                UserDetails userDetails = dbUserManager.loadUserByUsername(username);
                log.info("认证成功！用户"+username+" 角色权限为"+userDetails.getAuthorities().toString());

                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,null,userDetails.getAuthorities()
                );
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authToken);

                request.setAttribute(CommonConstant.USER_ID,id);
                response.setHeader(CommonConstant.USER_ID,String.valueOf(id));
            }
        } else if (Objects.equals(clientType,RequestHeaderConstant.TEACHER_CLIENT)) {
            claims = JwtUtil.parseJWT(jwtProperties.getTeacherSecretKey(), token);
            int id = (int) claims.get("id");
            String username = String.valueOf(claims.get("username"));
            if(username != null){
//            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = dbUserManager.loadUserByUsername(username);
                log.info("认证成功！用户" + username + " 角色权限为" + userDetails.getAuthorities().toString());

                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities()
                );
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authToken);

                request.setAttribute(CommonConstant.TEACHER_ID,id);
                response.setHeader(CommonConstant.TEACHER_ID, String.valueOf(id));
            }
        }
        filterChain.doFilter(request,response);
    }
}
